package com.irrigation.controller;

import com.irrigation.dto.IrrigationDecisionDto;
import com.irrigation.service.IrrigationDecisionService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/irrigation/decisions")
@RequiredArgsConstructor
public class IrrigationDecisionController {

    private final IrrigationDecisionService decisionService;

    @GetMapping
    public ResponseEntity<List<IrrigationDecisionDto>> getAllDecisions() {
        return ResponseEntity.ok(decisionService.getAllDecisions());
    }

    @GetMapping("/{id}")
    public ResponseEntity<IrrigationDecisionDto> getDecisionById(@PathVariable Long id) {
        return ResponseEntity.ok(decisionService.getDecisionById(id));
    }

    @GetMapping("/device/{deviceId}")
    public ResponseEntity<List<IrrigationDecisionDto>> getDecisionsByDeviceId(@PathVariable Long deviceId) {
        return ResponseEntity.ok(decisionService.getDecisionsByDeviceId(deviceId));
    }

    @GetMapping("/strategy/{strategyId}")
    public ResponseEntity<List<IrrigationDecisionDto>> getDecisionsByStrategyId(@PathVariable Long strategyId) {
        return ResponseEntity.ok(decisionService.getDecisionsByStrategyId(strategyId));
    }

    @GetMapping("/range")
    public ResponseEntity<List<IrrigationDecisionDto>> getDecisionsByTimeRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        return ResponseEntity.ok(decisionService.getDecisionsByTimeRange(startTime, endTime));
    }

    @PostMapping
    public ResponseEntity<IrrigationDecisionDto> createDecision(@RequestBody IrrigationDecisionDto decisionDto) {
        return ResponseEntity.ok(decisionService.createDecision(decisionDto));
    }

    @PutMapping("/{id}")
    public ResponseEntity<IrrigationDecisionDto> updateDecision(
            @PathVariable Long id, 
            @RequestBody IrrigationDecisionDto decisionDto) {
        return ResponseEntity.ok(decisionService.updateDecision(id, decisionDto));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDecision(@PathVariable Long id) {
        decisionService.deleteDecision(id);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/{id}/execute")
    public ResponseEntity<IrrigationDecisionDto> executeDecision(@PathVariable Long id) {
        return ResponseEntity.ok(decisionService.executeDecision(id));
    }
}
